﻿using System.Text;
using Adaptive.Agrona;

#pragma warning disable CS8618
namespace Unity.Type.BinaryType
{
    public sealed class MessageHeader
    {
        public const int EncodingSchemaId = 1;
        public const int EncodingSchemaVersion = 0;
        public const int Size = 8;

        private const ByteOrder DefaultByteOrder = ByteOrder.LittleEndian;

        private IMutableDirectBuffer _buffer;
        private int _offset;
        private int _actingVersion;

        public void Wrap(IMutableDirectBuffer buffer, int offset, int actingVersion)
        {
            _offset = offset;
            _actingVersion = actingVersion;
            _buffer = buffer;
        }
        
        public int ActingVersion => _actingVersion;

        public const int BlockLengthNullValue = 65535;
        public const int BlockLengthMinValue = 0;
        public const int BlockLengthMaxValue = 65534;

        public int BlockLength
        {
            get => _buffer.GetInt(_offset + 0, DefaultByteOrder);
            set => _buffer.PutInt(_offset + 0, value, DefaultByteOrder);
        }
        
        public const int TemplateIdNullValue = 65535;
        public const int TemplateIdMinValue = 0;
        public const int TemplateIdMaxValue = 65534;

        public int TemplateId
        {
            get => _buffer.GetInt(_offset + 2, DefaultByteOrder);
            set => _buffer.PutInt(_offset + 2, value, DefaultByteOrder);
        }


        public const int SchemaIdNullValue = 65535;
        public const int SchemaIdMinValue = 0;
        public const int SchemaIdMaxValue = 65534;

        public int SchemaId
        {
            get => _buffer.GetInt(_offset + 4, DefaultByteOrder);
            set => _buffer.PutInt(_offset + 4, value, DefaultByteOrder);
        }


        public const int VersionNullValue = 65535;
        public const int VersionMinValue = 0;
        public const int VersionMaxValue = 65534;

        public int Version
        {
            get => _buffer.GetInt(_offset + 6, DefaultByteOrder);
            set => _buffer.PutInt(_offset + 6, value, DefaultByteOrder);
        }


        public override string ToString()
        {
            var stringBuilder = new StringBuilder(100);
            BuildString(stringBuilder);
            return stringBuilder.ToString();
        }

        private void BuildString(StringBuilder builder)
        {
            if (_buffer == null)
            {
                return;
            }
            builder.Append('(');
            builder.Append("BlockLength=");
            builder.Append(BlockLength);
            builder.Append('|');
            builder.Append("TemplateId=");
            builder.Append(TemplateId);
            builder.Append('|');
            builder.Append("SchemaId=");
            builder.Append(SchemaId);
            builder.Append('|');
            builder.Append("Version=");
            builder.Append(Version);
            builder.Append(')');
        }
    }
}
